<template>
  <div class="dialout" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @changeType="changeType" :query="query" ref="child" @isFold="isShowFold" :isTimePeriod = "true" :isOther="true"></date-time>
              <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
              <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="serve">
                  <span class="prov">{{$t('public.province')}}：</span>
                  <el-checkbox :indeterminate="isIndeterminate" v-model.trim="checkAll" @change="handleCheckAllChange">{{$t('public.checkAll')}}</el-checkbox>
                  <div style="margin: 15px 0;"></div>
                  <el-checkbox-group v-model.trim="checkedProvinces" @change="handleCheckedProvincesChange">
                    <el-checkbox v-for="(province, index) in provinces" :key="index" :label="province" :name="province">{{province}}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </template>
            </unfold></div>
        </div>
      </div>
      <affix :label="$t('report.callOutAreaSurvey')"></affix>
      <div class="situation">
        <div class="wrap_pro">
          <div class="call_all">
            <span>{{$t('report.outCallSum')}}</span>
            <span class="all_num">{{callInAll}}</span>
          </div>
          <div class="wrap_top" v-show="serveNumData.length !== 0">
            <span>{{$t('report.callOutTopPro')}}</span>
            <ul>
              <li v-for="(item, index) in situation" :key="index">
                <span class="sum_name">{{item.name}}</span>
                <span class="sit_num">{{item.value}}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <affix :label="$t('report.calloutAreaReCity')"></affix>
    </div>
    <div class="tab" :id="id">
      <div class="export">
        <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">
            {{ $t('report.formalTitle') }}</el-button>
        <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

        <!-- <el-button class="primary_btn fr report_excel_btn"
          v-if="$store.getters.exportFromEnd"
          v-on:click.stop="exportExcel"
        >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

        <el-button class="primary_btn fr report_excel_btn"
          v-on:click.stop="exportXlsx"
        >{{$t('report.exportXls')}}</el-button>

        <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        <el-button class="primary_btn fr pdf" v-on:click.stop="flag">{{$t('report.returnPreviousPage')}}</el-button>
      </div>
      <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config, ...formulasConfig]"> </report-table>
  </div>
  <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
    <span>{{$t('report.reportExportTipTitle')}}</span>
    <span slot="footer" class="dialog-footer">
      <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
      <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
    </span>
  </el-dialog>
  <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_dialout_area_city" v-on:close="close" :headCustom="formulasConfig"></header-option>
  <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config"
      @closeFormulaDialog="closeFormulaDialog" reportName="呼出地域分布报表" :reportType="id" />
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import headerOption from '../base/headerOption.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, reportAreaProvince, mixData} from '@/utils/reportUtils.js'
  import {deepClone, getCallTimeLength, optionTimeTypeCheck, isHasFunc} from '@/utils/m7Utils.js'
  import reportTable from '../base/reportTable.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  import {sortBy} from 'lodash'
  export default {
    name: 'dialout',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        formulas: [], // 公式数据
        resData: [], // 返回数组暂存
        isFold: false, // 是否展示搜索条件
        situation: [], // 概况渲染数据
        callInAll: 0, // 呼入总数
        loading: false, // 查询时展示加载的开关
        id: 'call_report_dialout_area_city', // 查询id
        query: {}, // 查询条件时间信息等
        isShow: false, // 是否展示配置表头开关
        dialogVisible: false, // 导出pdf弹窗开关
        checkAll: true, // 省份全选绑定值
        checkedProvinces: [], // 省份绑定值
        isIndeterminate: false, // 全选样式调控值
        headOptions: { // 表头相关数据
          Config: []
        },
        headOptionsShow: {}, // 配置表头数据
        provinces: reportAreaProvince, // 省份数据
        sum: [], // 表格合计数据
        serveNumData: [], // 表格table除合计数据
        dateType:''
      }
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      // 自定义表头
      formulasConfig() {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      headerOption,
      reportTable,
      FormulaEditorDialog
    },
    props: [
      'condition'
    ],
    watch: {
      // 监测自定义公式变化 更新数据
      formulas(cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serveNumData || this.serveNumData.length === 0) {
          return
        }
        var queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        var myQuery = queryData.query
        let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
        this.sum = sum
        this.serveNumData = dataDeal
      }
      // 监测父组件传的查询条件查询
      // condition (current, old) {
      //   this.search1(current)
      // }
    },
    methods: {
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog() {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 子组件切换时间类型传上来得方法 
      changeType (type) {
        this.dateType = type
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 返回上页
      flag () {
        this.$emit('flag')
      },
      // 钻入进来执行的方法
      search1 () {
        let current = this.condition
        // 从父组件获取数据计算初始查询条件
        this.checkedProvinces = [current.province]
        // 向下传递搜索条件
        this.query = deepClone(current.Query)
        // 给时间插件赋值
        this.$refs.child.form = {
          timeType: current.Query.TimeType,
          yearReport: parseInt(current.Query.yearReport),
          monthReport: parseInt(current.Query.monthReport),
          dayReport: parseInt(current.Query.dayReport)
        }
        if (current.dateSource.timeType) {
          this.$refs.child.form.timeType = current.dateSource.timeType
          this.$refs.child.week = current.dateSource.week
        }
        this.$refs.child.formSource = current.dateSource
        this.$refs.child.timeCheck = current.Query.timePeriod || false
        this.$refs.child.timePeriodStart = current.Query.timePeriodStart || ''
        this.$refs.child.timePeriodEnd = current.Query.timePeriodEnd || ''
        // 如果时间为自定义
        if (current.Query.TimeType === 'other_half_hour') {
          if (current.Query.StartTime || current.Query.EndTime) {
            let StartTime = current.Query.StartTime.split(' ')[1] ? current.Query.StartTime.split(' ')[1] : ''
            let EndTime = current.Query.EndTime.split(' ')[1] ? current.Query.EndTime.split(' ')[1] : ''
            this.$refs.child.otherTimes = {
              beginTime: StartTime,
              endTime: EndTime,
              beginDate: current.Query.normalStartTime,
              endDate: current.Query.normalEndTime
            }
          } else {
            this.$refs.child.otherTimes = {
              beginTime: '',
              endTime: '',
              beginDate: '',
              endDate: ''
            }
          }
        }
        if (current.Query.TimeType === 'other') {
          // 周报查询，允许到天
          let message = checkTime(current.Query.StartTime, current.Query.EndTime, false, true) 
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        let data = {
          reportType: 'call_report_dialout_area_city',
          account: this.$store.state.session.user.account,
          query: current.Query
        }
        data.query.relayAreaCityCurrentProvince = current.province
        data.query.reportType = 'call_report_dialout_area_city'
        this.$store.dispatch('openDialoutArea', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          // 复制搜索条件避免传值渲染得时候影响父组件得条件
          this.query = deepClone(current.Query)
          this.query.timeType = this.query.TimeType
          // this.dealDate(res)
          this.search()
        })
      },
      // 获取查询条件
      getSearchQueryData () {
        if (this.checkedProvinces.length === 0) {
          this.isProvince()
          return
        }
        // 初始化查询条件
        let data = {
          reportType: 'call_report_dialout_area_city',
          account: this.$store.state.session.user.account
        }
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null;
          if (this.dateType === 'week') { // 周报允许到天
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        data['query'] = myQuery
        return data
      },
        // 获取合计和处理data
    getServeNumDataAndSum(myQuery) {
      let sum = { City: this.$t('report.total') }
      let tempData = deepClone(mixData(this.resData, this.formulas))
      for (let i in tempData) {
        let item = tempData[i]
        // 计算合计
        for (let j in item) {
          if (sum[j] === undefined) {
            sum[j] = 0
          }
          if (j !== 'City') {
            sum[j] += item[j]
          }
        }
        this.headOptions.Config.forEach((option, index) => {
          if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
              item[option.name] = `${item[option.name]}`
          }
          if (option.timeType && option.timeType === 'hhmmss') {
            item[option.name] = getCallTimeLength(item[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            item[option.name] = Math.round(item[option.name]) + 's'
          }
        })
      }
      sum = mixData([sum], this.formulas)
           sum[0].CallOutAcceptRate = sum[0].AccessCount === 0 ? '0%' : Math.round((sum[0].DealingCount / sum[0].AccessCount) * 100) + '%'
          sum[0].CallOutAverageTimeLength = Math.round(sum[0].CallTimeLength / sum[0].DealingCount) || 0
      this.headOptions.Config.forEach((option, index) => {
        if (option.timeType && option.timeType === 'hhmmss') {
          sum[0][option.name] = getCallTimeLength(sum[0][option.name])
        } else if (option.timeType && option.timeType === 'second') {
          sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
        } 
      })
      return {
        sum: sum,
        dataDeal: sortBy(tempData, 'Province'),
      }
        
        
    },
      // 查询或导出excel
      searchOrExport (isExport) {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var myQuery = data['query']

        this.loading = true
        delete myQuery.relayAreaCityCurrentProvince
        this.$store.dispatch('openDialoutArea', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
            
            if (resp.success) {
              this.formulas = resp.data.Formulas
              this.resData = res.data
            }
            if (isExport) {
              this.loading = false
              var headOptions = optionTimeTypeCheck(res.tableHeader)
              // let tempData = deepClone(res.data)
              let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
              // 排序之后合并合计数组
              var tableData = sortBy(dataDeal, 'ReportTime').concat(sum)

              var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

              var dh = XlsxUtil.getDownloadHelper(headers, tableData)
              var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
              dh.download(this.$t('report.callReportDialoutArea') + timeStamp)
            } else {
              this.dealDate(res)
            }
          })
        })
        
      },
      // 查询报表数据
      search () {
        this.searchOrExport()
      },
      // 导出数据
      exportXlsx () {
        this.searchOrExport(true)
      },
      // 处理查询数据
      dealDate (res) {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        var myQuery = data.query
        this.headOptions = optionTimeTypeCheck(res.tableHeader)
        this.sum = [{City: this.$t('report.total')}]
        let tempData = deepClone(res.data)
        this.situation = []
        if (!tempData || tempData.length === 0) {
          this.sum = [{}]
          this.callInAll = 0
          this.serveNumData = []
          this.loading = false
          return
        }
        tempData = sortBy(tempData, (item) => {
            return -item.AccessCount
        })
        let { sum, dataDeal } = this.getServeNumDataAndSum(myQuery)
        this.sum = sum
        this.serveNumData = sortBy(dataDeal, 'City')
        // 概况添加前五得省
        for (let i in tempData) {
          let item = tempData[i]
          if (i < 5) {
            this.situation.push({name: item._id, value: item.AccessCount})
          }
        }

        this.callInAll = this.sum[0].AccessCount || 0
        this.serveNumData = tempData
        this.loading = false
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 省份查询条件为空弹出提示
      isProvince () {
        this.$message.error(this.$t('report.searchProvince'))
      },
      // 配置表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_dialout_area_city').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportDialoutArea') + searchTime(this.query), id: this.id})
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_dialout_area_city'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'ReportDialoutAreaCityExport'
        myQuery.user = this.$store.state.session.user._id
        delete myQuery.relayAreaCityCurrentProvince
        let data = {
          Method: 'ReportDialoutAreaCityExport',
          Query: myQuery
        }
        this.$store.dispatch('exportCallDialoutAreaReport', data).then(() => {
        })
      },
      // 全选，参考饿了么
      handleCheckAllChange (event) {
        this.checkedProvinces = this.checkAll ? this.provinces : []
        this.isIndeterminate = false
      },
      // 点击选择省份触发的方法 参数选择省份值[]
      handleCheckedProvincesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.provinces.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.provinces.length
      }
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.handleCheckAllChange()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .serve
    .el-checkbox
      width 90px
  .formal
    margin-left 10px    
</style>
